package com.xone.collaboration.service.impl.process;

import com.alibaba.fastjson.JSON;
import com.xone.collaboration.dao.dataobject.Operation;
import com.xone.collaboration.dao.mapper.OperationMapper;
import com.xone.collaboration.service.OperationProcess;
import com.xone.collaboration.service.vo.OperationResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
@Order(1)
public class OperationStoreProcess  implements OperationProcess {

    @Autowired
    private OperationMapper operationMapper;

    @Override
    public OperationResult process(OperationContext context) {

        saveToDb(context);

        return OperationResult.of(true,null);
    }

    public void saveToDb(OperationContext context) {
        Runnable run = new Runnable(){
            @Override
            public void run() {
                Operation operation = new Operation();
                operation.setContent(JSON.toJSONString(context.elements));
                operation.setCreator(context.operator);
                operation.setGmtCreate(new Date());
                operation.setOperationId(UUID.randomUUID().toString());
                operation.setOpType(context.OpType.getValue());
                operation.setSketchpadId(context.getSketchId());
                operationMapper.insertSelective(operation);
            }
        };
        Thread thread = new Thread(run);
        thread.start();
    }

    @Override
    public boolean needRun(OperationContext context) {
        return true;
    }
}
